<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/8/12
 * Time: 11:40
 */
namespace App\Repositories;

use App\Models\RepaymentBill;
use App\Models\RepaymentPlan;
use App\Models\User;
use App\Models\UserCreditCard;
use Illuminate\Support\Facades\DB;

class RepaymentPlanRepository
{
    /**
     * 创建用户绑定的还款计划
     * @param array $params
     * @return mixed
     */
    public function create(array $params)
    {
        return RepaymentPlan::create($params);
    }

    /**
     * 根据id获取还款计划资料
     * @param $id
     * @return mixed
     */
    public function byId($id)
    {
        return RepaymentPlan::find($id);
    }

    public function insertGetId($params)
    {
        return RepaymentPlan::insertGetId($params);
    }

    /**
     * 根据账单id获取还款计划
     * @param $id
     * @return mixed
     */
    public function ByBillId($billId)
    {
        return RepaymentPlan::where([
            'repayment_bill_id' => $billId,
            'repayment_plan_status' => 1000
        ])->first();
    }

    public function isUsePlan($userId)
    {
        return RepaymentPlan::where([
            'user_id' => $userId,
            'repayment_plan_status' => 1002,
        ])->first();
    }

    /**
     * 根据账单id获取还款计划
     * @param $id
     * @return mixed
     */
    public function getOnePlan($planId, $userId)
    {
        return RepaymentPlan::where([
            'id' => $planId,
            'user_id' => $userId
        ])->first();
    }

    public function plan($planId, $userId)
    {
        return RepaymentPlan::where([
            'id' => $planId,
            'user_id' => $userId,
            'is_delete' => 0,
        ])->first();
    }

    /**
     * 更新状态
     * @param $id
     * @param $status
     * @return mixed
     */
    public function updateStatus($id, $status)
    {
        return RepaymentPlan::where('id', $id)->update([
            'repayment_plan_status' => $status,
            'update_plan_time' => time(),
        ]);
    }

    /**
     * 是否有待执行和执行中的记录
     * @param $billId
     * @return mixed
     */
    public function isHasRunOrNoRun($billId)
    {
        return RepaymentPlan::where('repayment_bill_id', $billId)
            ->whereIn('repayment_plan_status', [1000, 1001, 1005])
            ->orderBy('id', 'desc')
            ->get();
    }


    /**
     * 是否有待执行和执行中的记录
     * @param $userId
     * @return mixed
     */
    public function isExistRunOrNoRun($userId)
    {
        return RepaymentPlan::where('user_id', $userId)
            ->whereIn('repayment_plan_status', [1000, 1001, 1005])
            ->get()->toArray();
    }
    /**
     * 根据账单id找出还款计划
     * @param $billId
     * @return mixed
     */
    public function repaymentPlanRecord($billId)
    {
        return RepaymentPlan::where('repayment_bill_id', $billId)
            ->orderBy('id', 'desc')
            ->get()
            ->toArray();
    }

    public function repaymentPlan($userId, $creditCardId, $status = 0, $month = '', $page = 0, $limit = 5)
    {
        $page -= 1;
        $page = $page < 0 ? 0 : $page;
        $offset = $page * $limit;
        if ($status == 0) {
            $status = [1000, 1001, 1002, 1003, 1004, 1005];
        }
        return RepaymentBill::join('repayment_plan', 'repayment_bill.id', '=', 'repayment_plan.repayment_bill_id')
            ->where([
                'repayment_bill.user_id' => $userId,
                'repayment_bill.credit_card_id' => $creditCardId,
                'repayment_plan.is_delete' => 0,
            ])
            ->whereIn('repayment_plan.repayment_plan_status', $status)
            ->where(function ($query) use ($month) {
                if (!empty($month)) {
                    $startDate = date('Y-m-01', strtotime($month));
                    $startTime = strtotime($startDate);
                    $startDateEndTime = $startDate . ' 23:59:59';
                    $endTime =  strtotime("$startDateEndTime +1 month -1 day");
                    $query->whereBetween('repayment_plan.create_plan_time', [$startTime, $endTime]);
                }
            })
            ->offset($offset)
            ->limit($limit)
            ->orderBy('repayment_plan.id', 'desc')
            ->get()
            ->toArray();
    }

    public function getRepaymentList($request)
    {
        $page = $request->pageNumber - 1;
        $page = $page < 0 ? 0 : $page;
        $limit = $request->pageSize ? $request->pageSize : 50;
        $offset = $page * $limit;
        $query = RepaymentBill::from('repayment_bill as rb')
            ->join('repayment_plan as rp', 'rb.id', '=', 'rp.repayment_bill_id')
            ->join('passage as p', 'rp.passage_id', '=', 'p.id')
            ->select('rb.bill_sn', 'rb.credit_card_id', 'rb.repayment_bill_money',
                'rb.bill_date', 'rb.repayment_date', 'rb.lowest_repayment_money', 'rb.bill_status', 'rb.month_bill_date',
                'rp.*', 'p.id as passage_id', 'p.display_name as passage_name')
            ->where(function ($query) use ($request) {
                if (!empty($request->repayment_plan_status)) {
                    $query->where('rp.repayment_plan_status', $request->repayment_plan_status);
                }
                if (!empty($request->passage_id)) {
                    $query->where('rp.passage_id', $request->passage_id);
                }
                if (!empty($request->keyword)) {
                    switch ($request->field) {
                        case 'user_id':
                            $query->where('rp.user_id', $request->keyword);
                            break;
                        case 'plan_id':
                            $query->where('rp.id', $request->keyword);
                            break;
                        case 'plan_sn':
                            $query->where('rp.plan_sn', 'like', '%' . $request->keyword . '%');
                            break;
                        case 'idcard_number':
                            $userId = User::where('idcard_number', $request->keyword)->value('user_id');
                            $query->where('rp.user_id', $userId);
                            break;
                        case 'credit_card_id':
                            $query->where('rb.credit_card_id', $request->keyword);
                            break;
                        case 'credit_card_no':
                            $creditCardNo = UserCreditCard::where('bank_no', $request->keyword)->value('id');
                            $query->where('rb.credit_card_id', $creditCardNo);
                            break;
                        case 'repayment_days':
                            $query->where('rp.repayment_days', $request->keyword);
                            break;
                    }
                }
                if (!empty($request->bill_date_start) && !empty($request->bill_date_end)) {
                    $query->whereBetween('rb.bill_date', [strtotime($request->bill_date_start), strtotime($request->bill_date_end)]);
                }
                if (!empty($request->repayment_date_start) && !empty($request->repayment_date_end)) {
                    $query->whereBetween('rb.repayment_date', [strtotime($request->repayment_date_start), strtotime($request->repayment_date_end)]);
                }
                if (!empty($request->finish_plan_time_start) && !empty($request->finish_plan_time_end)) {
                    $query->whereBetween('rp.finish_plan_time', [strtotime($request->finish_plan_time_start), strtotime($request->finish_plan_time_end)]);
                }
            });
        $total = $query->count();
        $result = $query->latest('rp.id')
            ->offset($offset)
            ->limit($limit)
            ->get();
        return ['result' => $result, 'count' => $total];
    }
}